package com.jyw.web.controller.system;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.jyw.common.annotation.Anonymous;
import com.jyw.common.annotation.Log;
import com.jyw.common.constant.UserConstants;
import com.jyw.common.core.controller.BaseController;
import com.jyw.common.core.domain.AjaxResult;
import com.jyw.common.core.domain.CommonResult;
import com.jyw.common.core.domain.entity.SysDept;
import com.jyw.common.enums.BusinessType;
import com.jyw.common.exception.ServiceException;
import com.jyw.common.utils.StringUtils;
import com.jyw.common.utils.spring.SpringUtils;
import com.jyw.system.domain.dto.DeptAddDto;
import com.jyw.system.domain.dto.DeptEditDto;
import com.jyw.system.domain.vo.DeptCacheVo;
import com.jyw.system.domain.vo.DeptPrintVo;
import com.jyw.system.service.ISysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 部门信息
 *
 * @author system
 */
@RestController
@RequestMapping("/system/dept")
@Api(tags = "科室管理")
public class SysDeptController extends BaseController {
    @Resource
    private ISysDeptService deptService;
    /**
     * 微信网页地址
     */
    private final static String BUSINESS_CODE_URL = "business.code.url";

    /**
     * 科室报修地址
     */
    private final static String BUSINESS_CODE_DEPT = "business.code.dept";

    /**
     * 获取部门列表
     */
    @GetMapping("/print/{ids}")
    @ApiOperation("科室码打印")
    @PreAuthorize("@ss.hasPermi('system:dept:print')")
    public CommonResult<List<DeptPrintVo>> list(@PathVariable Long[] ids) {
        //查询科室内容
        List<SysDept> depts = deptService.listByIds(Arrays.asList(ids));
        //封装科室
        String baseUrl = SpringUtils.getRequiredProperty(BUSINESS_CODE_URL);
        String pageUrl = SpringUtils.getRequiredProperty(BUSINESS_CODE_DEPT);
        List<DeptPrintVo> collect = depts.stream().map(data -> {

            DeptPrintVo vo = new DeptPrintVo(data);
            //构建科室码内容
            String content = StrUtil.format("{}{}{}", baseUrl, pageUrl, data.getDeptId());
            try {
                String code = QrCodeUtil.generateAsBase64(content, QrConfig.create().setImg(ImageIO.read(new ClassPathResource("template/logo/logo.jpg").getInputStream())), QrCodeUtil.QR_TYPE_SVG);
                vo.setCode(code);
            } catch (IOException e) {
                logger.warn("获取logo失败",e);
                throw new ServiceException("科室码生成失败");
            }
            return vo;
        }).collect(Collectors.toList());

        return CommonResult.success(collect);
    }

    /**
     * 获取部门列表
     */
    @GetMapping("/list")
    @ApiOperation("科室列表")
    public CommonResult<List<SysDept>> list(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return CommonResult.success(depts);
    }

    /**
     * 根据科室简拼查询科室列表
     */
    @GetMapping("/getListByAbbreviation")
    @ApiOperation("根据科室简拼查询科室列表")
    public CommonResult<List<SysDept>> getListByAbbreviation(String abbreviation) {
        List<SysDept> list = deptService.getListByAbbreviation(abbreviation);
        return CommonResult.success(list);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @GetMapping(value = "/{deptId}")
    @ApiOperation("科室详情")
    public CommonResult<SysDept> getInfo(@PathVariable Long deptId) {
        deptService.checkDeptDataScope(deptId);
        return CommonResult.success(deptService.selectDeptById(deptId));
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增科室")
    public CommonResult add(@Validated @RequestBody DeptAddDto addDto) {
        SysDept dept = addDto.buildDept();
        if (!deptService.checkDeptNameUnique(dept)) {
            return CommonResult.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(getUsername());
        return CommonResult.success(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改科室")
    public CommonResult edit(@Validated @RequestBody DeptEditDto editDto) {
        SysDept dept = editDto.buildDept();
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (!deptService.checkDeptNameUnique(dept)) {
            return CommonResult.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(deptId)) {
            return CommonResult.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0) {
            return CommonResult.error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(getUsername());
        return CommonResult.success(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    @ApiOperation("删除部门")
    public CommonResult remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return CommonResult.warn("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return CommonResult.warn("部门存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        return CommonResult.success(deptService.deleteDeptById(deptId));
    }

    @ApiOperation("获取部门缓存")
    @GetMapping("cache")
    public CommonResult<List<DeptCacheVo>> cache() {
        return CommonResult.success(deptService.getCache());
    }
}
